﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
using CCWin;
using gregn6Lib;
 

namespace JajaRun
{
    public partial class FrmReport : CCSkinMain
    {


        public FrmReport()
        {
            InitializeComponent();


            //连接报表事件
            //Report.Initialize += new _IGridppReportEvents_InitializeEventHandler(ReportInitialize);
            //Report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord);
            //Report.GroupBegin += new _IGridppReportEvents_GroupBeginEventHandler(ReportGroupBegin);
            //Report.ProcessRecord += new _IGridppReportEvents_ProcessRecordEventHandler(ReportProcessRecord);
            //Report.SectionFormat += new _IGridppReportEvents_SectionFormatEventHandler(ReportSectionFormat);

            //4.连接报表取数事件
            Report.Initialize += new _IGridppReportEvents_InitializeEventHandler(initReport);
            Report.GroupEnd += new _IGridppReportEvents_GroupEndEventHandler(GroupEnd );

        }
        GridppReport Report = new GridppReport();//1定义一个新报表


       
        
        private void Form3_Load(object sender, EventArgs e)
        {
            //获取当前账套的名称
            IniHelper inihelp = new IniHelper(Application.StartupPath + "\\ConDB.ini");
           string  MyZhangtao = inihelp.ReadIniData("当前账套", "账套", "新建账套");
            Connection.ZhangTaoName = MyZhangtao;
            this.Text = string.Format("提成报表--[当前账套：{0}]",Connection.ZhangTaoName  );

            //读取当前账套的连接信息
            IniHelper ini = new IniHelper(Application.StartupPath + "\\ConDB.ini");
            Connection.Server = ini.ReadIniData(Connection.ZhangTaoName, "Server", ".");
            Connection.DataBase = ini.ReadIniData(Connection.ZhangTaoName, "Database", "JajaCy01");
            Connection.User = ini.ReadIniData(Connection.ZhangTaoName, "UserID", "sa");
            Connection.Password = ini.ReadIniData(Connection.ZhangTaoName, "Password", "");


            LoadTiCheng();


            //控制日期或时间的显示格式

            this.dtp_Begin.CustomFormat = "yyyy-MM-dd HH:mm:ss";
            this.dtp_End.CustomFormat = "yyyy-MM-dd HH:mm:ss";
            //使用自定义格式

            this.dtp_Begin.Format = DateTimePickerFormat.Custom;
            this.dtp_End.Format = DateTimePickerFormat.Custom;

            dtp_Begin.Value = DateTime.Now.Date;
            //填充服务员下拉列表
            var userList = Model.bm_User.Fetch("WHERE UserID<>'0000'");
            Model.bm_User u = new Model.bm_User();
            u.UserID = "";
            u.UserName = "";
            userList.Insert ( 0,u);
            cmb_WaiterID.DataSource = userList;
            cmb_WaiterID.ValueMember = "UserID";
            cmb_WaiterID.DisplayMember = "UserName";

            //是否显示明细
            chk_ShowDetaile.Checked = true;

          

        }
        TiCheng tc = new TiCheng();
        private void  LoadTiCheng()
        {
            string fileName = Application.StartupPath + "\\TiChengSetting.ini";
           
            tc.LoadFile(fileName);
          
        }
         

        private void initReport()//报表查询条件
        { 

            //设置查询SQL
            Report.DetailGrid.Recordset.QuerySQL = SQL;
             
        }

         

        //题成汇总参数
        double sumTc = 0;


        //分组结束事件
        private void GroupEnd(IGRGroup Group)
        {
            //MessageBox.Show("分组结束事件"+ Group.Name);




            //从报表中 获取实收金额
            double  s = Report.ControlByName("SumConsumePay").AsSummaryBox .Value  ;


            Double m = 0;



            ////根据实收金额 判断应该提成多少钱
            m = tc.GetTiChengMoney(s, tc.List);

            

            //向报表传递 提成金额
            Report.ParameterByName("TcMoney").AsFloat = m;



            if (Group.Name == "GroupByBillID")
            {
                //
                
                sumTc += m;
                Report.ParameterByName("SumTc").AsFloat = sumTc;
            }

            if (Group.Name == "GroupByWaiterID")
            {
                sumTc = 0;
            }
            
            


        }


        //报表查询SQL
        string SQL;



        private void LoadReport()
        {

            this.Cursor = Cursors.WaitCursor;

            axGRDisplayViewer1.Stop();


            //装载报表模板
            //2载入报表模板数据 是否显示明细
            if (chk_ShowDetaile.Checked)
            {
                Report.LoadFromFile(Application.StartupPath + "\\Report\\TiChengByBill_HeBing.grf");
            }

            else
            {
                Report.LoadFromFile(Application.StartupPath + "\\Report\\TiChengByBill_NoMx.grf");

            }

            //3.设置与数据库的连接串
            //Report.DetailGrid.Recordset.ConnectionString = "Provider=SQLOLEDB.1;Password=0000;Persist Security Info=True;User ID=SA;Initial Catalog=JajaCy01;Data Source=.;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=JZSERVER;Use Encryption for Data=False;Tag with column collation when possible=False";

            Report.DetailGrid.Recordset.ConnectionString = Connection.GetReportConnectionString();
            //MessageBox.Show(Report.DetailGrid.Recordset.ConnectionString);
            //5.设定查询显示器要显示的报表
            axGRDisplayViewer1.Report = Report;


            StringBuilder sb = new StringBuilder();
            //组合SQL
            sb.Append("select billItemID, i.BillID, MenuID, MenuName, MenuUnit, i.TableID, b.TableName, i.BigClassID, c.BigClassName, SmallClassID, OrigiPrice, MenuPrice, i.DiscountRate, MenuAmount, PayPrice, i.SumConsumePay, i.SumConsume, b.beginTime, OrderTime, b.CheckOutTime, isNull(WaiterID, '未指定') as WaiterID, isNull(WaiterName, '未指定') as WaiterName from bi_billitem as i join bi_bill as b on i.billid = b.billid    join mn_bigclass as c on i.BigClassID = c.BigClassID  ");
            //查询条件
            sb.AppendFormat("WHERE b.CheckOutTime>'{0}' AND b.CheckOutTime<='{1}' ", dtp_Begin.Text, dtp_End.Text);
            sb.Append(GetSQLPaiChuTiaoJian());//过滤一些菜品ID
            //MessageBoxEx.Show(GetSQLPaiChuTiaoJian());  
            //如果指定的服务员 则添加服务员查询条件
            if (!string.IsNullOrWhiteSpace(cmb_WaiterID.Text))
            {
                sb.AppendFormat(" AND WaiterID='{0}'", cmb_WaiterID.SelectedValue.ToString());
            }


            //添加排序条件
            sb.Append(" Order By WaiterID, i.BillID, i.BigClassID, i.MenuID ");


            SQL = sb.ToString();


            //传递参数  统计时间段
            Report.ParameterByName("BeginTime").AsDateTime = dtp_Begin.Value;
            Report.ParameterByName("EndTime").AsDateTime = dtp_End.Value;

            //设置查询SQL
            Report.DetailGrid.Recordset.QuerySQL = SQL;
            //启动报表
            axGRDisplayViewer1.Start();

            this.Cursor = Cursors.Default;
        }



        //查询按钮
        private void skinButton1_Click(object sender, EventArgs e)
        {

            LoadReport();

        }


        public List<string> PaiChuMenuID = new List<string>();



        /// <summary>
        /// 获取排除包桌的菜品ID 的查询条件 SQL 
        /// </summary>
        /// <returns></returns>
        private string GetSQLPaiChuTiaoJian()
        {

            IniHelper ini = new IniHelper(Application.StartupPath + "\\PaiChuMenu.ini");
            //System.Collections.Specialized.StringCollection sc = new System.Collections.Specialized.StringCollection();
            System.Collections.Specialized.NameValueCollection values = new System.Collections.Specialized.NameValueCollection();

            ini.ReadSectionValues(Connection.ZhangTaoName , values);

            StringBuilder sb = new StringBuilder();

            foreach (string  s in values)
            {
                sb.AppendFormat ("  AND  MenuID <>'{0}'  ",s );
               
            }
            return sb.ToString();
        }
         
        //工具栏 设置按钮
        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            try
            {
                Form4 frm = new Form4();
                frm.Owner = this;
                frm.Show();
            }
            catch (Exception)
            {

                 
            }
       
        }


        //导出PDF
        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            if (Report != null && Report.DetailGrid != null)
            {

                string path = Application.StartupPath;
                string filename = path + "\\Export\\提成统计报表(按单据金额)" + ".Pdf";
                Report.ExportDirect(GRExportType.gretPDF , filename, true, true);

                MessageBoxEx.Show("导出成功！文件位于：" + path);

            }

 
            
          

        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {

            
            if (Report != null && Report.DetailGrid != null)
            {


                axGRDisplayViewer1.Stop();
                GridppReport Report75 = new GridppReport();//1定义一个新报表
                Report75.LoadFromFile(Application.StartupPath + "\\Report\\TiChengByBill_75mm.grf");
                Report75.DetailGrid.Recordset.ConnectionString = Connection.GetReportConnectionString();

                //MessageBox.Show(Connection.GetReportConnectionString());
                Report75.DetailGrid.Recordset.QuerySQL = SQL;
                //MessageBox.Show(SQL);
                axGRDisplayViewer1.Report = Report75;
                axGRDisplayViewer1.Start();
                Report75.PrintPreview(true);


            }
        }


        //打印预览
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            if (Report != null && Report.DetailGrid != null)
            {
                Report.PrintPreview(true);
            }
        }


        //打印
        private void toolStripButton7_Click(object sender, EventArgs e)
        {

            if (Report != null && Report.DetailGrid != null)
            {
                Report.Print(true);
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            LoadReport();
        }

        private void toolStripButton8_Click(object sender, EventArgs e)
        {
            Form5 frm = new Form5();
            frm.Show();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
